package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.dto.InspectExecDto;
import com.foreverwin.mes.lims.model.InspecArray;
import com.foreverwin.mes.lims.vo.ProjectArrayVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.InspectExecService;
import com.foreverwin.mes.lims.model.InspectExec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Levy
 * @since 2020-02-28
 */
@Controller
@RequestMapping("/inspectExecs")
public class InspectExecController {
    private final Logger logger = LoggerFactory.getLogger(InspectExecController.class);

    @Autowired
    public InspectExecService inspectExecService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getInspectExecById(@PathVariable String id) {
        InspectExec result;
        try {
            result = inspectExecService.selectById(id);
        } catch (Exception e) {
            logger.error("getInspectExecById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getInspectExecList(InspectExec inspectExec){
        List<InspectExec> result;
        try {
            EntityWrapper<InspectExec> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectExec);
            result = inspectExecService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectExecList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getInspectExecPageList")
    public AjaxResult getInspectExecPageList(FrontPage<InspectExec> frontPage, InspectExec inspectExec){
        Page result;
        try {
            String site = CommonMethods.getSite();
            inspectExec.setSite(site);
            EntityWrapper<InspectExec> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectExec);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("taskId", frontPage.getGlobalQuery())
                    .or().like("sfc", frontPage.getGlobalQuery())
                    .or().like("item", frontPage.getGlobalQuery())
                    .or().like("itemDesc", frontPage.getGlobalQuery())
                    .or().like("createdUser", frontPage.getGlobalQuery())
                    .or().like("updatedUser", frontPage.getGlobalQuery())
        ;
            }
            result = inspectExecService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectExecPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存检验执行数据
     * @param jsonObject
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/doSave")
    public AjaxResult inspectExecSave(@RequestBody JSONObject jsonObject) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();

        try {

            String taskId = (String) jsonObject.get("taskId");
            String sfc = (String) jsonObject.get("sfc");
            String production = (String) jsonObject.get("production");
            String step = (String) jsonObject.get("step");
            List<Map> detail = (List<Map>) jsonObject.get("detail");

            if ( StringUtils.isBlank( taskId ) ){
                throw BusinessException.build("任务编号不能为空");
            }
            if ( StringUtils.isBlank( production ) ){
                throw BusinessException.build("产品编号不能为空");
            }
            if ( detail == null ){
                throw BusinessException.build("检验执行项目不能为空");
            }
            inspectExecService.doSave( site , user , taskId , sfc , production , step  , detail );

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }

        return AjaxResult.success("检验任务执行成功！");
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult inspectExecDelete(@PathVariable("id") String id){
        int count;
        try {
            count = inspectExecService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectExecDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = inspectExecService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectExecBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    @ResponseBody
    @GetMapping("/_getTaskData")
    public AjaxResult _getTaskData(String task) {
        InspectExecDto inspectExecDto = new InspectExecDto();
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        try {

            inspectExecDto =  inspectExecService.doSearch( site , task ,user);
        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(inspectExecDto);
    }

    @ResponseBody
    @GetMapping("/_getProjectArray")
    public AjaxResult _getProjectArray(String task ,String param) {
        List<ProjectArrayVo> maps = new ArrayList<>();
        String site = CommonMethods.getSite();
        try {
            maps = inspectExecService.findArrayByTask( site , task , param );

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(maps);
    }
}